package com.wg.dao;

import com.wg.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JdbcImpl implements Jdbcdao{
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    JdbcUtils jdbc = applicationContext.getBean("jdbcUtils", JdbcUtils.class);
    @Override
    public int addUser(User user) {
            int update = jdbc.getJdbc().update("insert into user(username,`password`,sex,likes,`group`) values (?,?,?,?,?)", user.getUsername(), user.getPassword(), user.getSex(), user.getLikes().get(0), user.getGroup());
            if(update > 0) {
                System.out.println("添加用户成功,用户信息为:" + user);
                return 1;
            }return 0;
    }
    @Override
    public int delUser(int id) {
        int update = jdbc.getJdbc().update("delete from user where id = ?", id);
        if(update > 0){
                System.out.println("删除用户成功,用户id为:" + id);
                return 1;
        }return 0;
        }
    @Override
    public int updateUser(User user) {
        int update = jdbc.getJdbc().update("update user set username = ? ,`password` = ? ,sex = ?,likes = ?,`group` = ?where id = ?", user.getUsername(),user.getPassword(),user.getSex(),user.getLikes().get(0),user.getGroup(),user.getId());
        if(update > 0){
            System.out.println("更新用户成功,新的用户信息为:" + user);
            return 1;
        }return 0;
    }

    @Override
    public ArrayList<User> selectAll() {
        ArrayList<String> list = new ArrayList<String>();
        ArrayList<User> Userlist = new ArrayList<User>();
        List<Map<String, Object>> maps = jdbc.getJdbc().queryForList("select * from user");
        int count = 0;
        for(Map<String, Object> map : maps){
            list = new ArrayList<String>();
            String likes = (String) maps.get(count).get("likes");
            String[] split = likes.split("#");
            for (String s : split) {
                list.add(s);
            }
            Userlist.add(new User((int)map.get("id"),(String)map.get("username"),(String)map.get("password"),(String)map.get("sex"),list,(String)map.get("group")));
            count++;
        }
       return Userlist;
    }
}
